//
//  XHLoginViewController3.m
//  XHLogin


#import "LoginVC.h"
#import "WCPopupLayerManager.h"
#import "AFNetworking.h"
#import "Singleton.h"
#import "FastCoder.h"
#import "UserInfoModel.h"
#import "FastCoder.h"
#import "JSONHTTPClient.h"
@interface LoginVC ()<UITextFieldDelegate>
@property (nonatomic, strong) MBProgressHUD *hud;
@property (nonatomic, strong) Singleton *center;

@end

@implementation LoginVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _center = [Singleton sharedSingleton];
    
    UIColor* mainColor = [UIColor colorWithRed:28.0/255 green:158.0/255 blue:121.0/255 alpha:1.0f];
    UIColor* darkColor = [UIColor colorWithRed:7.0/255 green:61.0/255 blue:48.0/255 alpha:1.0f];
    
    NSString* fontName = @"Avenir-Book";
    NSString* boldFontName = @"Avenir-Black";
    
    self.view.backgroundColor = mainColor;
    
    CGFloat W = 263*BWB_iPhone6;
    CGFloat X = ([UIScreen mainScreen].bounds.size.width - W)/2;
   
    
    
    
    _usernameField = [[UITextField alloc] initWithFrame:CGRectMake(X, 228, W, 41)];
    _usernameField.backgroundColor = [UIColor whiteColor];
    _usernameField.layer.cornerRadius = 3.0f;
    _usernameField.placeholder = @"  请输入邮箱";
    _usernameField.keyboardType = UIKeyboardTypeEmailAddress;
    _usernameField.font = [UIFont fontWithName:fontName size:16.0f];

    
    UIImageView* usernameIconImage = [[UIImageView alloc] initWithFrame:CGRectMake(9, 9, 24, 24)];
    usernameIconImage.image = [UIImage imageNamed:@"mail"];
    UIView* usernameIconContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 41, 41)];
    usernameIconContainer.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1.0];
    [usernameIconContainer addSubview:usernameIconImage];
    
    _usernameField.leftViewMode = UITextFieldViewModeAlways;
    _usernameField.leftView = usernameIconContainer;
    
    _passwordField = [[UITextField alloc] initWithFrame:CGRectMake(X, 277, W, 41)];
    _passwordField.backgroundColor = [UIColor whiteColor];
    _passwordField.layer.cornerRadius = 3.0f;
    _passwordField.placeholder = @"  请输入密码";
    _passwordField.font = [UIFont fontWithName:fontName size:16.0f];
    _passwordField.secureTextEntry = YES;

    
    UIImageView* passwordIconImage = [[UIImageView alloc] initWithFrame:CGRectMake(9, 9, 24, 24)];
    passwordIconImage.image = [UIImage imageNamed:@"lock"];
    UIView* passwordIconContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 41, 41)];
    passwordIconContainer.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1.0];
    [passwordIconContainer addSubview:passwordIconImage];
    
    _passwordField.leftViewMode = UITextFieldViewModeAlways;
    _passwordField.leftView = passwordIconContainer;
    
    
    _loginButton = [[UIButton alloc] initWithFrame:CGRectMake(X, 336, W, 52)];
    _loginButton.backgroundColor = darkColor;
    _loginButton.layer.cornerRadius = 3.0f;
    _loginButton.titleLabel.font = [UIFont fontWithName:boldFontName size:20.0f];
    [_loginButton setTitle:@"登录" forState:UIControlStateNormal];
    [_loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_loginButton setTitleColor:[UIColor colorWithWhite:1.0f alpha:0.5f] forState:UIControlStateHighlighted];
    [_loginButton addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
    
//    _forgotButton = [[UIButton alloc] initWithFrame:CGRectMake(X, 382, W, 62)];
//    _forgotButton.backgroundColor = [UIColor clearColor];
//    _forgotButton.titleLabel.font = [UIFont fontWithName:fontName size:12.0f];
//    [_forgotButton setTitle:@"Forgot Password?" forState:UIControlStateNormal];
//    [_forgotButton setTitleColor:darkColor forState:UIControlStateNormal];
//    [_forgotButton setTitleColor:[UIColor colorWithWhite:1.0 alpha:0.5] forState:UIControlStateHighlighted];
    
    _cancleButton = [[UIButton alloc] initWithFrame:CGRectMake(X, 382, W, 62)];
    _cancleButton.backgroundColor = [UIColor clearColor];
    _cancleButton.titleLabel.font = [UIFont fontWithName:fontName size:12.0f];
    [_cancleButton setTitle:@"取消登录" forState:UIControlStateNormal];
    [_cancleButton setTitleColor:darkColor forState:UIControlStateNormal];
    [_cancleButton setTitleColor:[UIColor colorWithWhite:1.0 alpha:0.5] forState:UIControlStateHighlighted];
    [_cancleButton addTarget:self action:@selector(cancle) forControlEvents:UIControlEventTouchUpInside];
    
    _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(X, 85, W, 45)];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.backgroundColor = [UIColor clearColor];
    _titleLabel.textColor =  [UIColor whiteColor];
    _titleLabel.font =  [UIFont fontWithName:boldFontName size:24.0f];
    _titleLabel.text = @"FOXYMOON";
    
    _subTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(X, 128, W, 25)];
    _subTitleLabel.textAlignment = NSTextAlignmentCenter;
    _subTitleLabel.backgroundColor = [UIColor clearColor];
    _subTitleLabel.textColor =  [UIColor whiteColor];
    _subTitleLabel.font =  [UIFont fontWithName:fontName size:14.0f];
    _subTitleLabel.text = @"Welcome back, please login below";
    
    
    [self.view addSubview:self.titleLabel];
    [self.view addSubview:self.subTitleLabel];
    [self.view addSubview:self.loginButton];
   // [self.view addSubview:self.forgotButton];
    [self.view addSubview:self.cancleButton];
    [self.view addSubview:self.usernameField];
    [self.view addSubview:self.passwordField];
}


//邮箱正则
- (BOOL) validateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

- (void)login {
    Log("--login");
        if (IsNilString(_usernameField.text)) {
            [[WCPopupLayerManager shareMg] showTextOnly:@"邮箱不能为空!" withView:self.view];
            return;
        }
        if(![self validateEmail:_usernameField.text]){
            [[WCPopupLayerManager shareMg] showTextOnly:@"邮箱格式有误!" withView:self.view];
            return;
        }
        if (IsNilString(_passwordField.text)) {
            [[WCPopupLayerManager shareMg] showTextOnly:@"密码不能为空!" withView:self.view];
            return;
        }
        if(_passwordField.text.length<6){
            [[WCPopupLayerManager shareMg] showTextOnly:@"密码不能少于六位数!" withView:self.view];
            return;
        }

    
  //调试
    //[self centerLoginEmail:@"qqq@qq.com" loginPassword:@"123456"];
    [self centerLoginEmail:_usernameField.text loginPassword:_passwordField.text];
    
}

- (void)cancle {
    Log(@"取消登录");
    [self dismissViewControllerAnimated:YES completion:nil];

}

- (void)centerGetUserInfo {
  
    MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showSimple:self.view];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSDictionary *param = @{
                            @"token":[[NSUserDefaults standardUserDefaults]objectForKey:@"token"]
                            };
    __weak typeof (self)weakSelf = self;

    //获取用户信息
    [manager GET:@"http://103.13.222.30/api/v3/user"
      parameters:param
        progress:nil
         success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             [hud hide:YES
              ];
             NSDictionary *userInfo = (NSDictionary *)responseObject[@"data"];
             UserInfoModel *userInfoModel = [[UserInfoModel alloc]initWithDictionary:userInfo error:nil];
             NSData *userInfoData = [FastCoder dataWithRootObject:userInfoModel];
             [[NSUserDefaults standardUserDefaults]setObject:userInfoData forKey:@"userInfoData"];
             [[WCPopupLayerManager shareMg] showTextOnly:@"用户信息下载成功！" withView:self.view];
             [weakSelf dismissViewControllerAnimated:YES completion:nil];
             weakSelf.center.isLogin = YES;
             weakSelf.center.userInfoModel = (UserInfoModel *)((NSData *)[[NSUserDefaults standardUserDefaults] objectForKey:@"userInfoData"]);
             if(weakSelf.blockIsSuccessLoginHandler)
             {
                    weakSelf.blockIsSuccessLoginHandler();
             }

             
         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
             [hud hide:YES
              ];
             //hud.detailsLabelText = error.localizedDescription;
              [[WCPopupLayerManager shareMg] showTextOnly:error.localizedDescription withView:self.view];
             weakSelf.center.isLogin = NO;
            
         }];
}


- (void)centerLoginEmail:(NSString *)EMAIL loginPassword:(NSString *)PASSWORD
{
    MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showSimple:[UIApplication sharedApplication].keyWindow];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *url = @"http://103.13.222.30/api/v3/login";
    NSDictionary *dict = @{
                           @"email":EMAIL,
                           @"password":PASSWORD
                           };
    [manager POST:url parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {} progress:^(NSProgress * _Nonnull uploadProgress) {} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [hud hide:YES];
        NSString *token = ((NSDictionary *)responseObject)[@"data"][@"token"];
        Log(@"token --> %@", token);
        [[NSUserDefaults standardUserDefaults]setObject:token forKey:@"token"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [self centerGetUserInfo];
        hud.detailsLabelText = @"登录成功";
        [hud hide:YES afterDelay:1.5f];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [hud hide:YES];
        //hud.detailsLabelText = error.localizedDescription;
        hud.detailsLabelText = @"登录失败";
        [hud hide:YES afterDelay:1.5f];
        
    }];
}
//add extra headers
/*
 使用JSONHttpClient进行请求。
 
 [[JSONHTTPClient requestHeaders] setValue:[[NSUserDefaults standardUserDefaults]objectForKey:@"token"] forKey:@"token"];
 
 //make post, get requests
 [JSONHTTPClient getJSONFromURLWithString:@"http://103.13.222.30/api/v3/user"
 params:param
 completion:^(id json, JSONModelError *err) {
 
 }];
 */

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
